package com.zx._01_基础._012_反射;

import java.util.Optional;
import java.util.concurrent.TimeUnit;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Fork;
import org.openjdk.jmh.annotations.Measurement;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import org.openjdk.jmh.annotations.Threads;
import org.openjdk.jmh.annotations.Warmup;
import org.openjdk.jmh.runner.Runner;
import org.openjdk.jmh.runner.RunnerException;
import org.openjdk.jmh.runner.options.Options;
import org.openjdk.jmh.runner.options.OptionsBuilder;

@BenchmarkMode(Mode.Throughput)
@Warmup(iterations = 3)
@Measurement(iterations = 5, time = 3, timeUnit = TimeUnit.SECONDS)
@Threads(8)
@Fork(2)
@OutputTimeUnit(TimeUnit.MILLISECONDS)
public class 获得当前方法名benchmark {

    public static void main(String[] args) throws RunnerException {
        Options opt = new OptionsBuilder()
                .include(获得当前方法名benchmark.class.getSimpleName())
                .build();
        new Runner(opt).run();
        /*
        Benchmark      Mode  Cnt     Score     Error   Units
        c.z._._.获.m1  thrpt   10   111.033 ±  10.422  ops/ms
        c.z._._.获.m2  thrpt   10   101.727 ±   7.378  ops/ms
        c.z._._.获.m3  thrpt   10  4532.135 ± 242.985  ops/ms        性能最好
        c.z._._.获.m4  thrpt   10  1061.841 ±  81.402  ops/ms
         */
    }

    @Benchmark
    @BenchmarkMode({Mode.Throughput})
    public void m1() {
        String methodName = Thread.currentThread().getStackTrace()[1].getMethodName();
    }

    @Benchmark
    @BenchmarkMode({Mode.Throughput})
    public void m2() {
        String methodName = new Throwable().getStackTrace()[0].getMethodName();
    }

    @Benchmark
    @BenchmarkMode({Mode.Throughput})
    public void m3() {
        String methodName = new Object() {
        }.getClass().getEnclosingMethod().getName();
    }

    @Benchmark
    @BenchmarkMode({Mode.Throughput})
    public void m4() {
        StackWalker walker = StackWalker.getInstance();
        Optional<String> optional = walker.walk(frames -> frames
                .findFirst()
                .map(StackWalker.StackFrame::getMethodName));
    }
}